package com.wswy.wzcx.ui.message;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.che.libcommon.ui.VOMessage;
import com.che.libcommon.ui.adapter.OnItemClickListener;
import com.che.libcommon.ui.loading.LoadingFragment;
import com.che.libcommon.utils.CollectionUtils;
import com.wswy.wzcx.R;
import com.wswy.wzcx.api.ConfigsKt;
import com.wswy.wzcx.model.DataCenter;
import com.wswy.wzcx.model.MessageMode;
import com.wswy.wzcx.module.base.Resource;
import com.wswy.wzcx.ui.main.community.detail.TopicDetailActivity;
import com.wswy.wzcx.ui.web.WebViewActivity;
import com.wswy.wzcx.utils.StringUtils;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by wangduheng26 on 2018/1/29.
 * wangduheng26@gmail.com
 */

public class MessageDetailFragment extends LoadingFragment {
    public static final String TAG = "MessageDetailFragment";
    public static final String MESSAGE_TYPE = "args.message_type";


    private RecyclerView recyclerView;
    private String type;

    @Override
    public String getFragmentTitle() {
        if (TextUtils.equals(type, MessageMode.MESSAGE_SYSTEM)){
            return getString(R.string.query_message);
        }else  if (TextUtils.equals(type,MessageMode.MESSAGE_USER)){
            return getString(R.string.system_message);
        }else if (TextUtils.equals(type,MessageMode.MESSAGE_SOCIAL)){
            return getString(R.string.social_message);
        }else {
            return super.getFragmentTitle();
        }
    }

    public static MessageDetailFragment newInstance(String type) {
        Bundle args = new Bundle();
        args.putString(MESSAGE_TYPE, type);
        MessageDetailFragment fragment = new MessageDetailFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final Context context = getContext();
        FrameLayout frameLayout = new FrameLayout(context);
        frameLayout.setBackgroundColor(ContextCompat.getColor(context,R.color.default_background_color));
        recyclerView = new RecyclerView(context);
        recyclerView.setId(R.id.recycler_view);
        frameLayout.addView(recyclerView);
        return frameLayout;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                final RecyclerView.Adapter adapter = parent.getAdapter();
                if (adapter != null && parent.getChildAdapterPosition(view) == adapter.getItemCount() - 1) {
                    outRect.bottom = 20;
                } else {
                    outRect.bottom = 0;
                }
            }
        });

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        final Bundle bundle = getArguments();
        if (bundle != null && bundle.containsKey(MESSAGE_TYPE)) {
            type = bundle.getString(MESSAGE_TYPE);
        }
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        MessageListViewModel messageListViewModel = ViewModelProviders.of(this)
            .get(MessageListViewModel.class);

        messageListViewModel.onCreate();

        messageListViewModel.load(type);

        //setupPage();


        final MessageListAdapter adapter = new MessageListAdapter(messageListViewModel.getPagination());
        adapter.setOnItemClickListener(new OnItemClickListener<MessageVO>() {
            @Override
            public void onItemClick(@NonNull View itemView, int position,
                @Nullable MessageVO messageVO) {

                if (messageVO != null){
                    handleItemClick(messageVO);
                }

            }
        });




        recyclerView.setAdapter(adapter);

        messageListViewModel.getMessagesLiveData().observe(this,
            new Observer<Resource<List<MessageVO>>>() {
                @Override
                public void onChanged(@Nullable Resource<List<MessageVO>> listResource) {

                    if (listResource != null){

                        if (listResource.isOk()){


                            if (listResource.isFirst() && CollectionUtils.isEmpty(listResource.getData())){
                                if (TextUtils.equals(type, MessageMode.MESSAGE_USER)) {
                                    showError(VOMessage.createEmpty(R.drawable.messages_default_empty, R.string.empty_sys_msg, 0));
                                } else if (TextUtils.equals(type, MessageMode.MESSAGE_SYSTEM)) {
                                    showError(VOMessage.createEmpty(R.drawable.activity_default_empty, R.string.empty_user_msg, 0));
                                } else if (TextUtils.equals(type,MessageMode.MESSAGE_SOCIAL)){
                                    showError(VOMessage.createEmpty(R.drawable.messages_default_empty, R.string.empty_social_msg, 0));
                                }
                            }else {
                                showData();
                                if (listResource.isFirst()){
                                    adapter.setNewData(listResource.getData());
                                }else {
                                    adapter.addData(listResource.getData());
                                }
                            }
                        }else if (listResource.isFirst() && listResource.hasError()){
                            showError(VOMessage.createEmpty(R.drawable.messages_default_empty,R.string.error_common,0));
                        }
                    }

                }
            });


    }

    @Override
    protected int getLoadingFrameId() {
        return R.id.recycler_view;
    }



    private void handleItemClick(MessageVO messageVO) {

            String url = messageVO.getDetail().targetUrl;
            String extendStr = messageVO.getDetail().extendStr;
            if (!TextUtils.isEmpty(url)) {
                WebViewActivity.startWebview(getContext(), url);
            } else if (messageVO.getSocialMsg() != null){
                //有社交消息

                SocialMsg socialMsg = messageVO.getSocialMsg();

                long topicId = StringUtils.parseLong(socialMsg.getBbsId(),0);

                if (topicId > 0){
                    TopicDetailActivity.Companion.start(getContext(),topicId,false);
                }

            } else if (!TextUtils.isEmpty(extendStr)) {
                try {
                    JSONObject obj = new JSONObject(extendStr);
                    String orderId = obj.optString("orderNo");
                    if (!TextUtils.isEmpty(orderId) && DataCenter.get().hasLogin()) {
                        String token = DataCenter.get().getUserMode().token;
                        String orderDetailUrl = TextUtils.concat(ConfigsKt.H5_ORDER_DETAIL(), "orderNo=", orderId, "&token=", token).toString();
                        WebViewActivity.startWebview(getContext(), "订单详情", orderDetailUrl, true);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

    }

    @Override
    public LoadingConfigure getConfigure() {
        return null;
    }
}
